import { onUnmounted, reactive, toRefs, watch } from 'vue';

const upperCaseRegExp = /^[A-Z]/;

function getCase(k, t) {
  return (
    (t === 'lowerCase' ? k[0].toLowerCase() : k[0].toUpperCase()) +
    k.substring(1)
  );
}
function getLowerCase(k) {
  return getCase(k, 'lowerCase');
}
function getUpperCase(k) {
  return getCase(k);
}

// function upperFirstPropsMappingExpose(refs, other = {}) {
//   Object.entries(refs ?? {}).forEach(([k, v], i, a) => {
//     let keyUpperCase = getUpperCase(k);
//     let keyLowerCase = getLowerCase(k);

//     if (upperCaseRegExp.test(k[0])) {
//       refs[keyUpperCase] = refs[keyLowerCase] ?? refs[keyUpperCase]; // 映射小写属性给大写
//     }
//   });

//   if (Object.prototype.hasOwnProperty.call(refs, 'modelValue')) {
//     // 映射 modelValue 给 value
//     refs['value'] = refs['Value'] = refs.modelValue;
//   }

//   Object.entries(other ?? {}).forEach(([k, v], i, a) => {
//     // 挂上额外的扩展
//     let keyUpperCase = getUpperCase(k);
//     let keyLowerCase = getLowerCase(k);
//     refs[k] = refs[keyUpperCase] = v;
//   });

//   return refs;
// }

function useMappingProps(props, expose) {

  const mappingProps = reactive({ ...props });

  const mappingExpose = toRefs(reactive({ ...props }));
  // if (Object.prototype.hasOwnProperty.call(mappingExpose, 'modelValue')) {
  //   mappingExpose['value'] = mappingExpose.modelValue;
  // }
  Object.entries(expose ?? {}).forEach(([k, v], i, a) => {
    mappingExpose[k] = v;
  });
  mappingExpose.toggleClass = v => {};
  mappingExpose.removeClass = v => {};
  mappingExpose.addClass = v => {};
  mappingExpose.style = v => {};

  Object.entries(props ?? {}).forEach(([k, v], i, a) => {
    watch(
      () => props[k],
      (a, b) => {
        // console.log('props', a, b);
        if (a !== b) {
          // mappingExpose[k] = toRef(mappingProps[keyLowerCase]);
          mappingProps[k] = props[k] ?? a;
        }
      },
      {
        immediate: true,
        // deep: true,
      },
    );

    watch(
      () => mappingExpose[k]?.value,
      (a, b) => {
        // console.log('mappingExpose', a, b);
        if (a !== b) {
          try {
            mappingProps[k] = a;
          }catch(e){}
         
        }
      },
      {
        // immediate: true,
        // deep: true,
      },
    );
  });

  onUnmounted(() => {});

  return [mappingProps, mappingExpose];
}

export default useMappingProps;
